local tArgs = {...}
local packages = config.load("/etc/tpm/package.dat")
local temp = config.load("/etc/tpm/packageInstalled.dat")
local found, value

if not security.getSU() then
 exception.throw("RestrictedOpsException")
 return
end

if #tArgs < 1 then
 gui.printAppInfo("tpm", "package name not specified")
 return
elseif not packages then
 gui.printAppInfo("tpm", "package.dat is missing or corrupt")
 log.writeMessage("package.dat unable to be traversed")
 return
elseif not temp then
 shell.executeScript("/etc/scripts/tpm-recache.tsf")
end


gui.printAppInfo("tpm", "traversing package.dat")
local ok, pack = search.traverseValue(packages, tArgs[1])
if ok and pack then
 found, value = search.traverseKey(temp, pack.name)
 if found and value then
  temp[value] = nil
 else
  gui.printAppInfo("tpm", "package missing")
  return
 end
 gui.printAppInfo("tpm", "found corresponding package")
 gui.printAppInfo("tpm", "removing API files [1/2]")
 local numapi = 1
 local numbin = 1
 local APIRemovalFlag = false
 for k,v in pairs(pack.apis) do
  if fs.exists(tpm.toPackageAPI(k)) and not fs.isDir(tpm.toPackageAPI(k)) then
   fs.delete(tpm.toPackageAPI(k))
   APIRemovalFlag = true
   gui.printAppInfo("tpm", "removed API "..k.." ["..tostring(numapi).."]")
  else
   gui.printAppWarning("tpm", "failed to remove API "..k)
  end
  numapi = numapi + 1
 end
 gui.printAppInfo("tpm", "removing binaries [2/2]")
 for k,v in pairs(pack.bins) do
  if fs.exists(tpm.toPackageBinary(k)) and not fs.isDir(tpm.toPackageBinary(k)) then
   fs.delete(tpm.toPackageBinary(k))
   gui.printAppInfo("tpm", "removed binary "..k.." ["..tostring(numbin).."]")
  else
   gui.printAppWarning("tpm", "failed to remove binary "..k)
  end
  numbin = numbin + 1
 end
 if APIRemovalFlag then
  if gui.request("Assemblies were removed, restart") then
   kernel.reboot(false)
  end
 end
 config.save(temp, "/etc/tpm/packageInstalled.dat")
 log.writeMessage("Removed package "..tArgs[1])
 gui.printAppSuccess("tpm", "package removed")
else
 gui.printAppInfo("tpm", "unable to find id for "..tArgs[1])
end